package com.dz.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.dz.reggie.common.BaseContext;
import com.dz.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")  // 配置过滤器名称和拦截路径
public class LoginCheckFilter implements Filter {

    // 路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1、获取本次请求URI
        String requestURI = request.getRequestURI();

        log.info("拦截到请求：{}", requestURI);
        // 定义不需处理的请求路径
        String[] urls =  new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "common/**",
                "/user/sendMsg",  // 移动端发送短信
                "/user/login"  // 移动端登入
        };

        //2. 判断本次请求是否需要处理
        boolean check = check(urls, requestURI);
        //2.1 无需处理，直接放行
        if (check){
            log.info("本次请求无需拦截：{}", requestURI);
            filterChain.doFilter(request, response);
            return;
        }
        //3 判断登入状态
        Object employee = request.getSession().getAttribute("empId");
        if ( employee != null) {
            log.info("用户已登入：{}", employee);
            // 将当前登入人的id设置到线程中，以供使用
            Long empId = (Long) employee;
            BaseContext.setCurrentId(empId);

            // 3.1 已登入则放行
            filterChain.doFilter(request, response);
            return;
        }
        // 用户登入放行，并将身份信息存入线程内
        Object user = request.getSession().getAttribute("user");
        if (user != null){
            log.info("用户已登入，id为：{}", user);
            Long userId = (Long) user;
            BaseContext.setCurrentId(userId);

            // 3.1 已登入则放行
            filterChain.doFilter(request, response);
            return;
        }
        // 3.2 未登入：返回响应信息给前端做处理
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

    }

    /**
     * 路径匹配：检查是否需要处理
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls, String requestURI){
        for (String url : urls){
            boolean match =   PATH_MATCHER.match(url, requestURI);
            if (match)
                return true;
        }
        return false;
    }
}
